var _			= require("../lib/underscore")._,
	directory 	= require("./directory"),
	sys 		= require("sys"),
	url 		= require('url');

var Disk = {};
Disk.dirs = [];

function sortFileSystems(a, b) {
	return a.root.length - b.root.length; 
}

Disk.addDirectory = function (dir) {
	this.dirs.push(dir);
	this.dirs.sort(sortFileSystems);
};

Disk.get = function (request, response, fn) {
	var disk = this;
	var path = url.parse(request.url, true).pathname;
	var dir = this.edir;

	for (var i = 0; i < this.dirs.length; i++) {
		if (path.indexOf(this.dirs[i].root) === 0 ) {
			dir = this.dirs[i];
		} 
	}
	dir.get(request, response, function (err, msg) {
		if (err) {
			sys.log(sys.inspect(err));
			disk.edir.get(request, response, fn);
		} else {
			fn(msg);
		}
	});
}

exports.createDisk = function () {
	var disk = _.beget(Disk);
	disk.edir = directory.createErrorDirectory();
	return disk;
};
